package com.eco.fanliapp.service;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.eco.fanliapp.common.response.ServerResponse;
import com.eco.fanliapp.entity.*;
import com.eco.fanliapp.utils.DateFormatUtils;
import com.eco.fanliapp.utils.EmojiUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 公共方法更新用户的金额
 */
@Component
@Slf4j
public class UpdateUserCommon {

    @Autowired
    private ISyUserMoneyService iSyUserMoneyService;

    @Autowired
    private ISyUserTaskService iSyUserTaskService;

    @Autowired
    private ISyTaskTypeService iSyTaskTypeService;

    @Autowired
    private ISyGoldExchangeService iSyGoldExchangeService;

    @Autowired
    private RedisLockService redisLockService;

    @Autowired
    private IAppUserRewardSetupService iAppUserRewardSetupService;

    @Autowired
    private RedisTemplateService redisTemplateService;
    @Autowired
    private ISyUserMoneyLogService syUserMoneyLogService;
    @Autowired
    private IAppUserService appUserService;
    //用到的接口

    /**
     * @param money        金额
     * @param userId       用户id
     * @param syTaskTypeId 任务类型id
     * @return
     */
    public int UpdateUserMoney(BigDecimal money, Long userId, Integer syTaskTypeId) {
        //redis锁-时间
        long startTimes = System.currentTimeMillis() + 1000 * 3;
        if (syTaskTypeId != 5) {
            //获取锁
            if (!redisLockService.lock(userId + "UpdateUserMoney" + syTaskTypeId, startTimes + "")) {
                log.info("操作频繁，用户Id={}，syTaskTypeId={}", userId, syTaskTypeId);
                return 0;
            }
        }
        int syUserMoneyNum = 0;
        boolean isUpdate = false;
        QueryWrapper<SyUserTask> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("task_type_id", syTaskTypeId);
        SyUserTask syUserTaskNew = new SyUserTask();
        List<SyUserTask> syUserTasks = iSyUserTaskService.list(queryWrapper);
        log.info("红包==用户增加金额------UpdateUserMoney");
        if (syUserTasks != null && syUserTasks.size() > 0) {

            if (syTaskTypeId == 1 && syUserTasks.get(0).getTaskStatus() != 5
                    && syUserTasks.get(0).getTaskStatus() != 6) {//新手任务
                isUpdate = true;
                log.info("红包==用户增加金额------isUpdate{}", isUpdate);
            } else if (syTaskTypeId == 2) {
                if (syUserTasks.get(0).getTaskStatus() == 5
                        || syUserTasks.get(0).getTaskStatus() == 6) {
                    return syUserMoneyNum;
                }
            } else if (syTaskTypeId == 3) {
                return syUserMoneyNum;
            } else if (syTaskTypeId == 1 && syUserTasks.get(0).getTaskStatus() == 5
                    && syUserTasks.get(0).getTaskStatus() != 6) {
                return syUserMoneyNum;
            }

        }

        //查询每日首购任务
        SyTaskType syTaskType = iSyTaskTypeService.selectSyTaskTypeById(syTaskTypeId);
        //首次查询用户钱中是否存在数据
        SyUserMoney oldSyUserMoney = iSyUserMoneyService.selectByUserId(userId);

        log.info("红包==用户增加金额------oldSyUserMoney", userId, oldSyUserMoney);
        if (oldSyUserMoney == null) {//添加
            SyUserMoney syUserMoney = new SyUserMoney();
            syUserMoney.setUserId(userId);
            syUserMoney.setCashBalanceAmount(money);
            syUserMoney.setCashTotalAmount(money);
            syUserMoney.setEnable(1);
            syUserMoneyNum = iSyUserMoneyService.insertSyUserMoney(syUserMoney);
            log.info("红包==用户增加金额1------syUserMoneyNum{}金额{}", syUserMoneyNum, money);
        } else {//修改
            syUserMoneyNum = iSyUserMoneyService.updateUserCashBalanceAmount(money, userId);
            log.info("红包==用户增加金额2------syUserMoneyNum{}金额{}", syUserMoneyNum, money);
        }
        log.info("红包==用户增加金额------syUserMoneyNum", userId, syUserMoneyNum);
        if (syUserMoneyNum > 0) {
            redisLockService.unlock(userId + "UpdateUserMoney" + syTaskTypeId, startTimes + "");
            if (syTaskTypeId == 1 && isUpdate) {
                syUserTaskNew.setTableId(syUserTasks.get(0).getTableId());
                syUserTaskNew.setTaskStatus(5);
                syUserTaskNew.setTaskRewardDate(new Date());
                iSyUserTaskService.updateById(syUserTaskNew);
                log.info("红包==用户增加金额3------syUserMoneyNum{}金额{}", syUserMoneyNum, money);
                return syUserMoneyNum;
            } else if (syTaskTypeId == 2 && syUserTasks != null && syUserTasks.size() > 0) {

                syUserTaskNew.setTableId(syUserTasks.get(0).getTableId());
                syUserTaskNew.setTaskStatus(5);
                syUserTaskNew.setTaskRewardDate(new Date());
                iSyUserTaskService.updateById(syUserTaskNew);
                log.info("红包==用户增加金额3------syUserMoneyNum{}金额{}", syUserMoneyNum, money);
                return syUserMoneyNum;
            }


            //增加日志
            SyUserTask syUserTask = new SyUserTask();
            syUserTask.setUserId(userId);
            syUserTask.setTaskTypeId(syTaskType.getTableId());
            syUserTask.setTaskType(syTaskType.getTaskType());
            syUserTask.setTaskRewardType(syTaskType.getTaskRewardType());
            syUserTask.setTaskStatus(5);
            syUserTask.setTaskRewardNum(syTaskType.getTaskRewardNum());
            syUserTask.setTaskRewardMoney(money);
            syUserTask.setTaskRewardDate(new Date());
            syUserTask.setEnable(1);
            int syUserTaskNum = iSyUserTaskService.insertsyUserTask(syUserTask);
            log.info("红包==用户增加金额4------syUserMoneyNum{}金额{}", syUserMoneyNum, money);
            return syUserMoneyNum;
        }
        log.info("红包==用户增加金额5------syUserMoneyNum{}金额{}", syUserMoneyNum, money);
        return syUserMoneyNum;
    }


    /**
     * 任务加金币 并 自动兑换**
     */
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public BigDecimal updateUserGoldExchangeMoney(Long userId, Integer syTaskTypeId, Integer goldNum, Integer taskType, Integer signDays, String remark) {

        //redis锁-时间
        long startTimes = System.currentTimeMillis() + 1000 * 60;

        //获取锁
        if (!redisLockService.lock("user_task_" + syTaskTypeId + "_" + userId, startTimes + "")) {
            return null;
        }

        if (syTaskTypeId == 6 || syTaskTypeId == 7 || syTaskTypeId == 8 || syTaskTypeId == 9 || syTaskTypeId == 10
                || syTaskTypeId == 12 || syTaskTypeId == 13 || syTaskTypeId == 14 || syTaskTypeId == 15) {
            QueryWrapper<SyUserTask> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", userId);
            queryWrapper.eq("task_type_id", syTaskTypeId);
            if (syTaskTypeId == 8 || syTaskTypeId == 7 || syTaskTypeId == 6 || syTaskTypeId == 10) {
                queryWrapper.eq("task_reward_date", DateFormatUtils.string2date(DateFormatUtils.getNowDateDay(new Date()) + " 00:00:00"));
            }

            List<SyUserTask> syUserTasks = iSyUserTaskService.list(queryWrapper);
            if (syUserTasks != null && syUserTasks.size() > 0) {
                return null;
            }
        }

        //添加任务日志
        SyUserTask syUserTask = new SyUserTask();
        syUserTask.setUserId(userId);
        syUserTask.setTaskTypeId(syTaskTypeId);
        syUserTask.setTaskType(taskType);
        syUserTask.setTaskRewardType(2);
        syUserTask.setTaskStatus(5);
        syUserTask.setTaskRewardNum(goldNum);
        syUserTask.setTaskRewardDate(new Date());
        syUserTask.setEnable(1);
        if (signDays != null) {
            syUserTask.setTaskSignDay(signDays);
        }
        int taskStatus = iSyUserTaskService.insertsyUserTask(syUserTask);
        log.info("任务加金币==用户加金币日志用户id{}任务类型{}", userId, syTaskTypeId);
        int addMoneyStatus = 0;
        //日志添加成功，加金币
        String redisKeyStr = "user_money_cash_gold_lock_" + syTaskTypeId + "_" + userId;
        //redis锁-时间
        long times = System.currentTimeMillis() + 1000 * 3;
        if (taskStatus > 0) {
            //user_money_cash_gold_lock_userId 金币钱包锁
            //获取锁
            if (!redisLockService.lock(redisKeyStr, times + "")) {
                return null;//锁存在
            }
            addMoneyStatus = iSyUserMoneyService.updateUserGoldBalanceAmount(goldNum, userId);
            log.info("任务加金币==用户修改金币用户id{}结果{}金币{}任务类型{}", userId, addMoneyStatus, goldNum, syTaskTypeId);
        }

        if (addMoneyStatus > 0) {
            //自动兑换
            redisLockService.unlock(redisKeyStr, times + "");
            BigDecimal exchangeMoney = iSyGoldExchangeService.getUserTaskGoldExchangeMoney(userId, remark);
            if (exchangeMoney != null) {
                return exchangeMoney;
            }
        }
        return null;
    }

    /**
     * （红包） 加钱sy_user_money
     *
     * @param money        金额
     * @param userId       用户id
     * @param syTaskTypeId 任务类型id
     * @return
     */
    public int updateUserMoneyByTaskId(BigDecimal money, Long userId, Integer syTaskTypeId, String remark) {
        //redis锁-时间
        long startTimes = System.currentTimeMillis() + 1000 * 3;

        //获取锁
        if (!redisLockService.lock("user_task_" + userId + "_" + syTaskTypeId, startTimes + "")) {
            log.info("任务锁，用户Id={}，syTaskTypeId={}", userId, syTaskTypeId);
            return 0;
        }
        //判断任务是否完成，根据任务syTaskType判断，记录日志
        QueryWrapper<SyUserTask> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("task_type_id", syTaskTypeId);
        SyUserTask syUserTaskNew = new SyUserTask();
        List<SyUserTask> syUserTasks = iSyUserTaskService.list(queryWrapper);
        if (syUserTasks != null && syUserTasks.size() > 0) {
            //判断是否完成
            if (syTaskTypeId == 1) {
                if (syUserTasks.get(0).getTaskStatus() == 5 || syUserTasks.get(0).getTaskStatus() == 6) {//新手任务0.36
                    return 0;
                }
            } else if (syTaskTypeId == 2) {
                if (syUserTasks.get(0).getTaskStatus() == 5
                        || syUserTasks.get(0).getTaskStatus() == 6) {
                    return 0;
                }
            } else if (syTaskTypeId == 3) {
                return 0;
            }
        }
        //查询任务对照表
        SyTaskType syTaskType = iSyTaskTypeService.selectSyTaskTypeById(syTaskTypeId);
        int syUserTaskStatus = 0;

        if (syTaskTypeId == 2 && syUserTasks != null && syUserTasks.size() > 0) {
            syUserTaskNew.setTableId(syUserTasks.get(0).getTableId());
            syUserTaskNew.setTaskStatus(5);
            syUserTaskNew.setTaskRewardDate(new Date());
            Boolean stakStatus = iSyUserTaskService.updateById(syUserTaskNew);
            if (stakStatus) {
                syUserTaskStatus = 1;
            }
        } else {
            //增加日志
            SyUserTask syUserTask = new SyUserTask();
            syUserTask.setUserId(userId);
            syUserTask.setTaskTypeId(syTaskType.getTableId());
            syUserTask.setTaskType(syTaskType.getTaskType());
            syUserTask.setTaskRewardType(syTaskType.getTaskRewardType());
            syUserTask.setTaskStatus(5);
            syUserTask.setTaskRewardNum(syTaskType.getTaskRewardNum());
            syUserTask.setTaskRewardMoney(money);
            syUserTask.setTaskRewardDate(new Date());
            syUserTask.setEnable(1);
            syUserTaskStatus = iSyUserTaskService.insertsyUserTask(syUserTask);
        }
        if (syUserTaskStatus > 0) {
            //日志记录成功，给用户加钱
            //user_money_cash_lock_userId user_money钱包锁
            String redisKeyStr = "user_money_cash_lock_" + userId;
            //redis锁-时间
            long times = System.currentTimeMillis() + 1000 * 3;
            if (!redisLockService.lock(redisKeyStr, times + "")) {
                return 0;//锁存在
            }
            //加钱
            int updateCashBalanceStatus = iSyUserMoneyService.updateUserCashBalanceAmount(money, userId);
            if (updateCashBalanceStatus > 0) {
                redisLockService.unlock(redisKeyStr, null);
                //首次查询用户钱中是否存在数据
                SyUserMoney syUserMoney = iSyUserMoneyService.selectByUserId(userId);
                //加钱记录log日志
                syUserMoneyLogService.addSyUserMoneyLog(userId, syUserMoney.getCashBalanceAmount(), money, remark, null, 0);
                return 1;
            } else {
                //添加推送，log日志
                log.error("红包，账户余额修改失败==用户id{}money{}times{}", userId, money, new Date());
                List<String> appUserIdList = new ArrayList<>();
                appUserIdList.add("600190267390");//冲哥
                appUserIdList.add("600543669140");//LYL
                appUserIdList.add("600332065180");//77
                appUserIdList.add("601421401081");//祝超
                appUserIdList.add("601404133785");//王跃
                JpushMessage.jiGuangPushMesageListAndroid(10001, EmojiUtil.resolveToEmojiFromByte("红包加钱失败"), appUserIdList, EmojiUtil.resolveToEmojiFromByte(userId + "***" + money), 4001, null, null);
                JpushMessage.jiGuangPushMesageListIos(10001, EmojiUtil.resolveToEmojiFromByte("红包加钱失败"), appUserIdList, EmojiUtil.resolveToEmojiFromByte(userId + "***" + money), 4001, null, null);
            }

        } else {
            log.error("任务日志插入失败userId{},任务类型{}", userId, syTaskTypeId);
        }
        return 0;
    }

    /**
     * 修改首单红包状态**
     */
    public int UpdateUserTaskStatus(Long userId, Integer syTaskStatus) {
        //redis锁-时间
        long startTimes = System.currentTimeMillis() + 1000 * 3;

        //获取锁
        if (!redisLockService.lock(userId + "UpdateUserTaskStatus", startTimes + "")) {
            log.info("操作频繁，用户Id={}，syTaskStatus={}", userId, syTaskStatus);
            return 0;
        }
        //增加或修改任务日志状态
        log.info("修改首单任务状态---------UpdateUserTaskStatus");
        QueryWrapper<SyUserTask> queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("task_type_id", 2);
        SyUserTask syUserTask = null;

        AppUserRewardSetup rewardSetup = null;
        if (redisTemplateService.hasKey("AppUserRewardSetup")) {
            rewardSetup = redisTemplateService.getTByKey("AppUserRewardSetup", AppUserRewardSetup.class);
        } else {
            rewardSetup = iAppUserRewardSetupService.getById(1);
            redisTemplateService.set("AppUserRewardSetup", rewardSetup, 60 * 60);
        }

        try {
            syUserTask = iSyUserTaskService.selectOne(queryWrapper);
            log.info("修改首单任务状态---------syUserTask{}", syUserTask);
            if (syUserTask != null) {
                SyUserTask userTask = new SyUserTask();
                userTask.setTableId(syUserTask.getTableId());
                userTask.setTaskStatus(syTaskStatus);//3已下单，4待入账，5完成奖励到账
                userTask.setTaskRewardDate(new Date());
                iSyUserTaskService.updateById(userTask);
                log.info("修改首单任务状态1---------userTask{}", userTask);
                return 1;
            } else {
                SyUserTask userTask = new SyUserTask();
                userTask.setTaskStatus(syTaskStatus);
                userTask.setUserId(userId);
                userTask.setTaskTypeId(2);
                userTask.setTaskType(1);
                userTask.setTaskRewardType(1);
                userTask.setTaskRewardNum(0);
                userTask.setTaskRewardDate(new Date());
                userTask.setEnable(1);
                userTask.setDeleted(0);
                userTask.setTaskRewardMoney(rewardSetup.getTaskRedMoneyAmount());
                int task2 = iSyUserTaskService.insertsyUserTask(userTask);
                log.info("新增首单任务状态1---------userTask{}", userTask);
                return 1;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    public int updateUserBalanceMoney(BigDecimal money, Long userId, int syTaskTypeId) {
        QueryWrapper<SyUserTask> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("task_type_id", syTaskTypeId);
        List<SyUserTask> syUserTasks = iSyUserTaskService.list(queryWrapper);

        if (syUserTasks != null && syUserTasks.size() > 0) {
            return 0;
        }
        //查询任务
        SyTaskType syTaskType = iSyTaskTypeService.selectSyTaskTypeById(syTaskTypeId);
        //查询用户
        AppUser appUser = appUserService.selectAppUserByUserId(userId, 0);

        log.info("红包==用户增加金额------userMoney", userId, money);
        if (appUser != null) {
            //修改用户余额
            appUserService.updateAppUseraddbalance(userId, money);
        }

        //增加日志
        SyUserTask syUserTask = new SyUserTask();
        syUserTask.setUserId(userId);
        syUserTask.setTaskTypeId(syTaskType.getTableId());
        syUserTask.setTaskType(syTaskType.getTaskType());
        syUserTask.setTaskRewardType(syTaskType.getTaskRewardType());
        syUserTask.setTaskStatus(5);
        syUserTask.setTaskRewardNum(syTaskType.getTaskRewardNum());
        syUserTask.setTaskRewardMoney(money);
        syUserTask.setTaskRewardDate(new Date());
        syUserTask.setEnable(1);
        int syUserTaskNum = iSyUserTaskService.insertsyUserTask(syUserTask);
        return 0;

    }

}
